package com.example.userwallet.service.Impl;

import com.example.userwallet.enums.WalletRecordType;
import com.example.userwallet.mapper.UserMapper;
import com.example.userwallet.mapper.WalletRecordMapper;
import com.example.userwallet.pojo.User;
import com.example.userwallet.pojo.WalletRecord;
import com.example.userwallet.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author:Nyapii
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final WalletRecordMapper walletRecordMapper;

    public UserServiceImpl(UserMapper userMapper, WalletRecordMapper walletRecordMapper) {
        this.userMapper = userMapper;
        this.walletRecordMapper = walletRecordMapper;
    }

    @Override
    public BigDecimal getUserBalance(Long userId) {
        User user = userMapper.getUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        return user.getBalance();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean consume(Long userId, BigDecimal amount) {
        User user = userMapper.getUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (user.getBalance().compareTo(amount) < 0) {
            throw new IllegalArgumentException("余额不足");
        }
        user.setBalance(user.getBalance().subtract(amount));
        int rows = userMapper.updateUser(user);
        if (rows != 1) {
            throw new RuntimeException("扣款失败");
        }
        WalletRecord walletRecord = new WalletRecord();
        walletRecord.setUserId(userId);
        walletRecord.setType(WalletRecordType.CONSUME.getType());
        walletRecord.setAmount(amount.negate()); // 消费为负数
        walletRecordMapper.addWalletRecord(walletRecord);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refund(Long userId, BigDecimal amount) {
        User user = userMapper.getUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        user.setBalance(user.getBalance().add(amount));
        int rows = userMapper.updateUser(user);
        if (rows != 1) {
            throw new RuntimeException("退款失败");
        }
        WalletRecord walletRecord = new WalletRecord();
        walletRecord.setUserId(userId);
        walletRecord.setType(WalletRecordType.REFUND.getType());
        walletRecord.setAmount(amount);
        walletRecordMapper.addWalletRecord(walletRecord);
        return true;
    }

    @Override
    public List<WalletRecord> getUserWalletRecords(Long userId) {
        return walletRecordMapper.getWalletRecordsByUserId(userId);
    }
}